from django.http import HttpResponse, JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from staff_management.models import Employee
from divisional_management.models import Department
import json
import html

class EmpView(View):
    def get_dept_name(self,dep_id):
        # 根据dep_id查找部门名称
        try:
            print('calling get_dept_name()',dep_id)
            dep=Department.objects.get(id=dep_id)
        except:
            return '此部门不存在'
        return dep.dep_name

    def make_emp_res(self,emp:Employee):
    # 将单个员工信息封装成前端需要的JSON格式
        print('-------make_emp_res()',emp.emp_id)
        emp_info={}
        emp_info['emp_id'] = emp.emp_id
        emp_info['name'] = emp.name
        emp_info['gender'] = '女' if emp.gender else '男'
        emp_info['birthday'] = emp.birthday
        emp_info['id_number'] = emp.id_number
        emp_info['nationality'] = emp.nationality
        emp_info['entry_date'] = emp.entry_date
        emp_info['post'] = emp.post
        emp_info['edu'] = emp.edu
        emp_info['mariage'] = '已婚' if emp.gender else '未婚'
        emp_info['address'] = emp.address
        emp_info['dept'] = self.get_dept_name(emp.dep_id_id)
        emp_info['phone'] = emp.phone
        emp_info['email'] = emp.email
        res={'code':200,'data':emp_info}
        return res

    def make_emps_res(self,emps_list):
    # 将查询结果封装成前端需要的JSON格式
        emps_res=[]
        for emp in emps_list:
            d={}
            d['emp_id']=emp.emp_id
            d['name']=emp.name
            d['gender']='女' if emp.gender else '男'
            d['birthday']=emp.birthday
            d['post']=emp.post
            d['dept']=self.get_dept_name(emp.dep_id_id)
            d['phone']=emp.phone
            d['email']=emp.email
            emps_res.append(d)
        res={'code':200,'data':emps_res}
        return res

    # def get(self, request):
    #     # # 获取部门数据库数据,返回给员工添加页面
    #     results = [{'code': 200}]
    #     department = Department.objects.all()
    #     for d in department:
    #         results.append({'dep_id':d.dep_id,'dep_name':d.dep_name})
    #         # results.append({'dep_id': 'd.dep_id', 'dep_name':'d.dep_name'})
    #     return JsonResponse(results,safe=False)

    def get(self,request):
        # 获取员工信息
        emp_id = request.GET.get('emp_id')
        if emp_id:
            # 根据emp_id获取单个员工的全部信息
            try:
                emp = Employee.objects.get(emp_id=emp_id)
            except:
                result = {'code': 402, 'msg': '获取单个员工信息失败!'}
                return JsonResponse(result)
            # 将单个员工信息封装成前端需要的JSON格式
            res=self.make_emp_res(emp)
            print(res)
            return JsonResponse(res)

        else:
            # 获取员工列表
            emps_list=Employee.objects.all()
            # 将查询结果封装成前端需要的JSON格式
            res=self.make_emps_res(emps_list)
            print(res)
            return JsonResponse(res)

    def post(self,request):
        # 1.先获取json串
        json_str = request.body
        # 2.将字符串反序列化为对象
        py_obj = json.loads(json_str)
        # # 3.获取每一个数据
        # 名字
        name=py_obj['name']
        # 员工编号：
        emp_id=py_obj['emp_id']
        # 性别  0 为男 1为女
        gender=py_obj['gender']
        if not gender:
            results = {'code': 10003, 'error': '请选择性别!'}
            return JsonResponse(results)
        gender=bool(int(gender))
        # 出生日期：
        birthday=py_obj['birthday']
        # 身份证号：
        id_number=py_obj['id_number']
        # 民族：
        nationality=py_obj['nationality']
        # 身高：
        height=py_obj['height']
        # 体重：
        weight=py_obj['weight']
        # 入职时间：
        entry_date=py_obj['entry_date']
        # 学历
        edu=py_obj['edu']
        # 婚姻状况 0 为已婚 1为未婚
        marriage=py_obj['marriage']
        if not marriage:
            results = {'code': 100012, 'error': '请选择婚姻状况!'}
            return JsonResponse(results)
        marriage=bool(int(marriage))
        # 住址
        address=py_obj['address']
        address = html.escape(address)
        # 电话
        phone=py_obj['phone']
        # 邮箱
        email=py_obj['email']
        # 职位
        post = py_obj['post']
        # 判断是否选择部门
        dep = py_obj['dep']
        # 进行数据校验
        # print('------------------------', name, emp_id, gender, birthday, id_number, nationality, height
        #       , weight, entry_date, post, edu, marriage, address, phone, email,dep)
        if not name:
            results={'code':10001,'error':'名字不能为空!'}
            return JsonResponse(results)
        if not emp_id:
            results = {'code': 10002, 'error': '员工编号不能为空!'}
            return JsonResponse(results)

        if not birthday:
            results = {'code': 10004, 'error': '出生日期不能为空!'}
            return JsonResponse(results)
        if not id_number:
            results = {'code': 10005, 'error': '省份证不能为空!'}
            return JsonResponse(results)
        if not nationality:
            results = {'code': 10006, 'error': '民族不能为空!'}
            return JsonResponse(results)
        if not height:
            results = {'code': 10007, 'error': '身高不能为空!'}
            return JsonResponse(results)
        if not weight:
            results = {'code': 10008, 'error': '体重不能为空!'}
            return JsonResponse(results)
        if not entry_date:
            results = {'code': 10009, 'error': '入职时间不能为空!'}
            return JsonResponse(results)
        if not post:
            results = {'code': 100010, 'error': '岗位不能为空!'}
            return JsonResponse(results)
        if not edu:
            results = {'code': 100011, 'error': '学历不能为空!'}
            return JsonResponse(results)
        if not address:
            results = {'code': 100013, 'error': '地址不能为空!'}
            return JsonResponse(results)
        if not phone:
            results = {'code': 100014, 'error': '电话不能为空!'}
            return JsonResponse(results)
        if not email:
            results = {'code': 100015, 'error': '邮件不能为空!'}
            return JsonResponse(results)
        if not dep:
            results = {'code': 100016, 'error': '请选择部门!'}
            return JsonResponse(results)
        # # 数据入库
        # # 对地址进行转码防止xxs攻击
        # 获取部门数据库
        try:
            department = Department.objects.get(dep_id=dep)
            print('部门id',department.dep_id)
        except:
            print('没有该部门')
        # 获取部门编号
        try:
            employees = Employee.objects.create(
                emp_id=emp_id,
                name=name,
                gender=gender,
                birthday=birthday,
                id_number=id_number,
                nationality=nationality,
                height=height,
                weight=weight,
                entry_date=entry_date,
                post=post,
                edu=edu,
                marriage=marriage,
                address=address,
                phone=phone,
                email=email,
                is_active=True,
                # 外键关联前端获取到的部门数据 与Department数据库对比 编号
                # 或则 前端部门返回Department数据库的编号
                dep_id=department
                # dep_id=Department  #外键绑定部门id
                )
            print('创建员工详情',employees)

        except Exception as e:
            print('错误信息',e)
            results = {'code': 100016, 'error': '该用户已被创建!'}
            return JsonResponse(results)
        return JsonResponse({'code':200})

    def delete(self,request):
        # 根据查询字符串中的emp_id删除指定员工
        emp_id=request.GET.get('emp_id')
        print('--------calling delete()',emp_id)
        try:
            emp=Employee.objects.get(emp_id=emp_id)
            emp.delete()
            result = {'code': 200, 'msg': '删除成功!'}
            print(result)
        except:
            result={'code':401,'msg':'删除失败!'}
        return JsonResponse(result)

    def put(self,request):
        # 根据查询字符串中的emp_id修改指定员工信息
        emp_id = request.GET.get('emp_id')
        print('--------calling put()',emp_id)
        try:
            emp=Employee.objects.get(emp_id=emp_id)

            result = {'code': 201, 'msg': '更新员工信息成功!'}
        except:
            result={'code':402,'msg':'更新员工信息失败!'}
        return JsonResponse(result)
